package logic.nodes.lod;

import java.util.HashMap;

import logic.nodes.BoundController;

import com.jme.bounding.BoundingBox;
import com.jme.bounding.BoundingVolume;
import com.jme.math.Vector3f;
import com.jme.scene.TriMesh;

public class TriMeshBoundController extends BoundController {
	
	private static final long serialVersionUID = 1L;
	
	private TriMesh mesh;
	private LODNode parentLODNode;
	private HashMap<TriMesh, BoundingVolume> meshBounds;
	private HashMap<TriMesh, Vector3f> meshDirs;
	
	public TriMeshBoundController(TriMesh mesh, LODNode parentLODNode, 
			HashMap<TriMesh, BoundingVolume> meshBounds, HashMap<TriMesh, Vector3f> meshDirs) {
		super(parentLODNode);
		this.mesh = mesh;
		this.parentLODNode = parentLODNode;
		this.meshBounds = meshBounds;
		this.meshDirs = meshDirs;
	}
	
	@Override
	protected boolean ready() {
		return mesh.getWorldBound() != null 
		&& mesh.getWorldBound() instanceof BoundingBox 
		&& parentLODNode.getBound() != null;
	}
	
	@Override
	protected void performAction(float time) {
		BoundingVolume vol = mesh.getWorldBound().clone(null);
		meshBounds.put(mesh, vol);
		Vector3f meshCenter = vol.getCenter();
		Vector3f nodeCenter = parentLODNode.getBound().getCenter();
		float dist = meshCenter.distance(nodeCenter);
		float nodeSize = parentLODNode.getSize() * 2f;
		if(dist > nodeSize) parentLODNode.localToWorld(meshCenter, meshCenter);
		Vector3f dir = meshCenter.subtract(nodeCenter);
		meshDirs.put(mesh, dir);
	}
}